# alg.py - 岛屿数量计算算法（使用类封装）

class Solution:
    def numIslands(self, grid):
        """
        计算二维网格中岛屿的数量
        :param grid: 二维列表，元素为 '1'（陆地）或 '0'（水）
        :return: 岛屿数量
        """
        if not grid or not grid[0]:
            return 0
        
        rows = len(grid)
        cols = len(grid[0])
        count = 0
        
        def dfs(r, c):
            """深度优先搜索，将相连的陆地标记为已访问"""
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
                return
            grid[r][c] = "#"  # 标记为已访问
            dfs(r+1, c)
            dfs(r-1, c)
            dfs(r, c+1)
            dfs(r, c-1)
        
        # 遍历每个单元格
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1":
                    count += 1
                    dfs(r, c)
        
        return count

def read_grid_from_file(filename):
    """
    从文件读取网格数据
    :param filename: 文件名
    :return: 二维网格列表
    """
    try:
        with open(filename, 'r') as file:
            grid = []
            for line in file:
                line = line.strip()
                if line:
                    grid.append(list(line))
            return grid
    except FileNotFoundError:
        print("错误：文件 {} 不存在".format(filename))
        return None
    except Exception as e:
        print("错误：读取文件 {} 时发生异常 - {}".format(filename, str(e)))
        return None